<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { 
  Monitor, Avatar, List, SuccessFilled, Loading, DataAnalysis, 
  Document, InfoFilled, WarningFilled, CircleCheckFilled 
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { analyticsAPI } from '@/utils/api'
import StatusCard from '@/components/StatusCard/index.vue'

// 响应式数据
const loading = ref({
  chart: false,
  stats: false
})

const chartTimeRange = ref('7d')

const deviceStats = ref({
  online: 0,
  total: 0
})

const accountStats = ref({
  active: 0,
  total: 0
})

const taskStats = ref({
  running: 0,
  today: 0,
  completed: 0,
  successRate: 0
})

const systemStatus = ref({
  uptime: '0天 0小时',
  cpu: 0,
  memory: 0,
  disk: 0
})

const recentActivities = ref([
  {
    id: '1',
    type: 'success',
    title: '设备连接成功',
    timestamp: new Date().toISOString()
  },
  {
    id: '2',
    type: 'info',
    title: '任务自动调度启动',
    timestamp: new Date(Date.now() - 300000).toISOString()
  },
  {
    id: '3',
    type: 'warning',
    title: '账号登录失败',
    timestamp: new Date(Date.now() - 600000).toISOString()
  }
])

// 定时器
let statusTimer: number | null = null

// 方法
const loadDashboardData = async() => {
  loading.value.stats = true
  try {
    // 获取仪表板统计数据
    const stats = await analyticsAPI.getDashboardStats()
    
    // 更新统计数据
    deviceStats.value = {
      online: stats.devices?.online || 0,
      total: stats.devices?.total || 0
    }
    
    accountStats.value = {
      active: stats.accounts?.active || 0,
      total: stats.accounts?.total || 0
    }
    
    taskStats.value = {
      running: stats.tasks?.running || 0,
      today: stats.tasks?.today || 0,
      completed: stats.tasks?.completed || 0,
      successRate: stats.tasks?.successRate || 0
    }
  } catch (error) {
    console.error('Failed to load dashboard data:', error)
    // 使用模拟数据
    deviceStats.value = { online: 2, total: 5 }
    accountStats.value = { active: 8, total: 12 }
    taskStats.value = { running: 3, today: 15, completed: 45, successRate: 95 }
  } finally {
    loading.value.stats = false
  }
}

const loadSystemStatus = () => {
  // 模拟系统状态数据
  systemStatus.value = {
    uptime: '2天 14小时',
    cpu: Math.floor(Math.random() * 30) + 10,
    memory: Math.floor(Math.random() * 40) + 30,
    disk: Math.floor(Math.random() * 20) + 60
  }
}

const getActivityIcon = (type: string) => {
  const icons = {
    success: CircleCheckFilled,
    info: InfoFilled,
    warning: WarningFilled,
    error: WarningFilled
  }
  return icons[type as keyof typeof icons] || InfoFilled
}

const formatTime = (timestamp: string) => {
  return dayjs(timestamp).format('MM-DD HH:mm')
}

const startStatusUpdates = () => {
  statusTimer = setInterval(() => {
    loadSystemStatus()
  }, 5000) // 每5秒更新系统状态
}

const stopStatusUpdates = () => {
  if (statusTimer) {
    clearInterval(statusTimer)
    statusTimer = null
  }
}

// 生命周期
onMounted(async() => {
  await loadDashboardData()
  loadSystemStatus()
  startStatusUpdates()
})

onUnmounted(() => {
  stopStatusUpdates()
})

// 监听时间范围变化
watch(chartTimeRange, () => {
  // 重新加载图表数据
  console.log('Chart time range changed:', chartTimeRange.value)
})
</script>

<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">仪表板</h1>
      <p class="page-description">查看系统整体运行状态和关键指标</p>
    </div>

    <!-- 统计卡片 -->
    <ElRow :gutter="20" class="stats-row">
      <ElCol :xs="24" :sm="12" :md="6">
        <StatusCard
          title="在线设备"
          :value="deviceStats.online"
          :suffix="`/${deviceStats.total}`"
          color="#67c23a"
          :icon="Monitor"
          trend="up"
          :trend-value="`${Math.round((deviceStats.online / Math.max(deviceStats.total, 1)) * 100)}%`"
        />
      </ElCol>
      <ElCol :xs="24" :sm="12" :md="6">
        <StatusCard
          title="活跃账号"
          :value="accountStats.active"
          :suffix="`/${accountStats.total}`"
          color="#409eff"
          :icon="Avatar"
          trend="neutral"
        />
      </ElCol>
      <ElCol :xs="24" :sm="12" :md="6">
        <StatusCard
          title="运行中任务"
          :value="taskStats.running"
          color="#e6a23c"
          :icon="List"
          trend="up"
          :trend-value="`今日: ${taskStats.today}`"
        />
      </ElCol>
      <ElCol :xs="24" :sm="12" :md="6">
        <StatusCard
          title="完成率"
          :value="taskStats.successRate"
          suffix="%"
          color="#67c23a"
          :icon="SuccessFilled"
          trend="up"
          :trend-value="`${taskStats.completed} 已完成`"
        />
      </ElCol>
    </ElRow>

    <!-- 主要内容区域 -->
    <div class="dashboard-content">
      <el-row :gutter="20">
        <el-col :span="16">
          <!-- 任务状态图表 -->
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>任务执行趋势</span>
                <el-radio-group v-model="chartTimeRange" size="small">
                  <el-radio-button label="7d">最近7天</el-radio-button>
                  <el-radio-button label="30d">最近30天</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div class="chart-container">
              <div v-if="loading.chart" class="loading-container">
                <el-icon class="is-loading"><Loading /></el-icon>
                <span class="loading-text">加载中...</span>
              </div>
              <div v-else class="chart-placeholder">
                <el-icon class="empty-icon"><DataAnalysis /></el-icon>
                <p class="empty-text">图表数据加载中...</p>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <!-- 系统状态 -->
          <el-card class="status-card" shadow="hover">
            <template #header>
              <span>系统状态</span>
            </template>
            <div class="status-list">
              <div class="status-item">
                <div class="status-label">系统运行时间</div>
                <div class="status-value">{{ systemStatus.uptime }}</div>
              </div>
              <div class="status-item">
                <div class="status-label">CPU 使用率</div>
                <div class="status-value">
                  <el-progress 
                    :percentage="systemStatus.cpu" 
                    :stroke-width="6"
                    :show-text="false"
                  />
                  <span class="progress-text">{{ systemStatus.cpu }}%</span>
                </div>
              </div>
              <div class="status-item">
                <div class="status-label">内存使用率</div>
                <div class="status-value">
                  <el-progress 
                    :percentage="systemStatus.memory" 
                    :stroke-width="6"
                    :show-text="false"
                    color="#67C23A"
                  />
                  <span class="progress-text">{{ systemStatus.memory }}%</span>
                </div>
              </div>
              <div class="status-item">
                <div class="status-label">磁盘使用率</div>
                <div class="status-value">
                  <el-progress 
                    :percentage="systemStatus.disk" 
                    :stroke-width="6"
                    :show-text="false"
                    color="#E6A23C"
                  />
                  <span class="progress-text">{{ systemStatus.disk }}%</span>
                </div>
              </div>
            </div>
          </el-card>

          <!-- 最近活动 -->
          <el-card class="activity-card" shadow="hover">
            <template #header>
              <span>最近活动</span>
            </template>
            <div class="activity-list">
              <div 
                v-for="activity in recentActivities" 
                :key="activity.id"
                class="activity-item"
              >
                <div class="activity-icon" :class="activity.type">
                  <el-icon>
                    <component :is="getActivityIcon(activity.type)" />
                  </el-icon>
                </div>
                <div class="activity-content">
                  <div class="activity-title">{{ activity.title }}</div>
                  <div class="activity-time">{{ formatTime(activity.timestamp) }}</div>
                </div>
              </div>
              
              <div v-if="recentActivities.length === 0" class="empty-activities">
                <el-icon class="empty-icon"><Document /></el-icon>
                <p class="empty-text">暂无活动记录</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  .stat-content {
    display: flex;
    align-items: center;
    gap: 16px;
  }
  
  .stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    
    &.online {
      background: var(--el-color-success-light-9);
      color: var(--el-color-success);
    }
    
    &.active {
      background: var(--el-color-primary-light-9);
      color: var(--el-color-primary);
    }
    
    &.running {
      background: var(--el-color-warning-light-9);
      color: var(--el-color-warning);
    }
    
    &.success {
      background: var(--el-color-success-light-9);
      color: var(--el-color-success);
    }
  }
  
  .stat-info {
    flex: 1;
    
    .stat-value {
      font-size: 28px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      line-height: 1;
      margin-bottom: 4px;
    }
    
    .stat-label {
      font-size: 14px;
      color: var(--el-text-color-regular);
      margin-bottom: 2px;
    }
    
    .stat-total {
      font-size: 12px;
      color: var(--el-text-color-placeholder);
    }
  }
}

.dashboard-content {
  flex: 1;
}

.chart-card {
  height: 400px;
  
  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  
  .chart-container {
    height: 320px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .chart-placeholder {
    text-align: center;
    color: var(--el-text-color-placeholder);
    
    .empty-icon {
      font-size: 48px;
      margin-bottom: 16px;
    }
  }
}

.status-card {
  margin-bottom: 20px;
  
  .status-list {
    .status-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 12px 0;
      border-bottom: 1px solid var(--el-border-color-lighter);
      
      &:last-child {
        border-bottom: none;
      }
      
      .status-label {
        font-size: 14px;
        color: var(--el-text-color-regular);
      }
      
      .status-value {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .el-progress {
          width: 80px;
        }
        
        .progress-text {
          font-size: 12px;
          color: var(--el-text-color-regular);
          min-width: 35px;
          text-align: right;
        }
      }
    }
  }
}

.activity-card {
  .activity-list {
    .activity-item {
      display: flex;
      align-items: flex-start;
      gap: 12px;
      padding: 12px 0;
      border-bottom: 1px solid var(--el-border-color-lighter);
      
      &:last-child {
        border-bottom: none;
      }
      
      .activity-icon {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
        flex-shrink: 0;
        
        &.success {
          background: var(--el-color-success-light-9);
          color: var(--el-color-success);
        }
        
        &.info {
          background: var(--el-color-info-light-9);
          color: var(--el-color-info);
        }
        
        &.warning {
          background: var(--el-color-warning-light-9);
          color: var(--el-color-warning);
        }
        
        &.error {
          background: var(--el-color-danger-light-9);
          color: var(--el-color-danger);
        }
      }
      
      .activity-content {
        flex: 1;
        
        .activity-title {
          font-size: 14px;
          color: var(--el-text-color-primary);
          margin-bottom: 4px;
        }
        
        .activity-time {
          font-size: 12px;
          color: var(--el-text-color-placeholder);
        }
      }
    }
    
    .empty-activities {
      text-align: center;
      padding: 40px 0;
      color: var(--el-text-color-placeholder);
      
      .empty-icon {
        font-size: 32px;
        margin-bottom: 8px;
      }
      
      .empty-text {
        font-size: 14px;
      }
    }
  }
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .dashboard-content {
    .el-col {
      margin-bottom: 20px;
    }
  }
}
</style>